package com.amoby.base.utils.ftp;

import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class FTPPool<T> {
    private GenericObjectPool<T>    pool;
    // private ThreadLocal<T> threadLocal;
    private PooledObjectFactory<T>  factory;
    private GenericObjectPoolConfig poolConfig;

    public T currentResource() throws Exception {
        // T t = this.threadLocal.get();
        // if (t == null) {
        // t = (T) this.pool.borrowObject();
        // this.threadLocal.set(t);
        // }
        return this.pool.borrowObject();
    }

    public void returnResource(T resource) throws Exception {
        // this.threadLocal.remove();
        this.pool.returnObject(resource);
    }

    public void init() {
        // defaults to make your life with connection pool easier :)
        // poolConfig.setTestWhileIdle(true);
        // poolConfig.setMinEvictableIdleTimeMillis(60000);
        // poolConfig.setTimeBetweenEvictionRunsMillis(30000);
        // poolConfig.setNumTestsPerEvictionRun(-1);
        this.pool = new GenericObjectPool<T>(factory, poolConfig);
        // 初始连接
        // try {
        // this.pool.addObject();
        // } catch (Exception e) {
        // throw new RuntimeException(e);
        // }
        // this.threadLocal = new ThreadLocal<T>();
    }

    public void destroy() throws Exception {
        this.pool.close();
    }

    public int inPoolSize() {
        return this.pool.getNumIdle();
    }

    public int borrowSize() {
        return this.pool.getNumActive();
    }

    public PooledObjectFactory<T> getFactory() {
        return this.factory;
    }

    public GenericObjectPoolConfig getPoolConfig() {
        return this.poolConfig;
    }

    public void setFactory(PooledObjectFactory<T> factory) {
        this.factory = factory;
    }

    public void setPoolConfig(GenericObjectPoolConfig poolConfig) {
        this.poolConfig = poolConfig;
    }
}
